<template>
    <div class="edit-popup">
        <popup ref="popupRef" :title="popupTitle" :async="true" width="60%" @confirm="handleSubmit" @close="handleClose">
            <el-form ref="formRef" :model="formData" label-width="120px" :rules="formRules">
                <el-form-item :label="$t('语言分类')" prop="client_id">
                    <el-select class="flex-1" v-model="formData.client_id" :placeholder="$t('请选择语言分类')"
                        :disabled="mode === 'edit'">
                        <el-option v-for="(item, index) in props.clientOptions" :key="index" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('翻译语句')" prop="code">
                    <el-input class="w-[280px]" v-model="formData.code" :placeholder="$t('翻译语句')"
                        :disabled="mode === 'edit'" />
                    <el-button type="primary" class="ml-2" @click="autoTranslate">{{ $t('一键翻译') }}</el-button>
                </el-form-item>

                <el-card class="!border-none mt-4" shadow="never">
                    <el-table size="large" class="mt-4" :data="formData.list">
                        <el-table-column :label="$t('语言类型')" prop="type_id" min-width="50" align="left">
                            <template #default="{ row }">
                                {{ row.type_text }}
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('对应翻译')" prop="after_text" min-width="100%" align="left">
                            <template #default="{ row }">
                                <el-input v-model="row.after_text" :placeholder="$t('请输入译文')"></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup>
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const props = withDefaults(
    defineProps<{
        clientOptions: any[]
        langOptions: any[]
    }>(),
    {
        clientOptions: () => [],
        langOptions: () => [],
    }
)
import type { FormInstance } from 'element-plus'
import { translateEdit, translateAdd, translateDetail, apiAutoTranslate } from '@/api/setting/lang'
import Popup from '@/components/popup/index.vue'
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

const popupTitle = computed(() => {
    return mode.value == 'edit' ? t('编辑语句') : t('新增语句')
})
const formData = reactive({
    id: '',
    client_id: '',
    code: '',
    list: [] as any
})

const formRules = {
    client_id: [
        {
            required: true,
            message: t('请选择语言分类'),
            trigger: ['blur']
        }
    ],
    code: [
        {
            required: true,
            message: t('请输入翻译语句'),
            trigger: ['blur']
        }
    ],
}

const autoTranslate = async () => {
    const translateRes = await apiAutoTranslate({
        code: formData.code,
        lang_list: props.langOptions.map((item) => item.file_name)
    });

    for (const key in formData.list) {
        const item = formData.list[key];
        console.log(item, item['lang_code'], translateRes[formData.list[key]['lang_code']])
        formData.list[key]['after_text'] = translateRes[item.lang_code]
    }
    console.log(formData.list)
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    mode.value == 'edit' ? await translateEdit(formData) : await translateAdd(formData)
    popupRef.value?.close()
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const getCodeValue = (type_id: number, field = 'file_name') => {
    const langTypeItem = props.langOptions.find((item) => item.id === type_id)
    // 获取组合中文名称
    if (field === 'type_text') {
        return langTypeItem ? `${langTypeItem.language_name}(${langTypeItem.file_name})` : ''
    }
    return langTypeItem ? langTypeItem.file_name : ''
}

const initForm = () => {
    for (const key in props.langOptions) {
        const langType = props.langOptions[key]
        if (!formData.list[key]) {
            formData.list[key] = {
                type_id: langType.id,
                lang_code: getCodeValue(langType.id, 'file_name'),
                type_text: getCodeValue(langType.id, 'type_text'),
                after_text: ""
            }
        }
    }
}

const setFormData = (data: Record<any, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    for (const key in formData.list) {
        const item = formData.list[key]
        formData.list[key]['lang_code'] = getCodeValue(item.type_id, 'file_name')
        formData.list[key]['type_text'] = getCodeValue(item.type_id, 'type_text')
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await translateDetail({
        id: row.id,
        code: row.code,
        client_id: row.client_id,
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    initForm,
    setFormData,
    getDetail
})
</script>
